package com.fs.activiti5.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipInputStream;

import javax.transaction.Transactional;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.log4j.Log4j;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.fs.activiti5.vo.Affair;
import com.fs.activiti5.vo.TaskVo;
import com.fs.base.repository.OrgRepository;
import com.fs.base.repository.SqlRepository;
import com.fs.base.service.BaseService;
import com.fs.base.utils.ApplicationUtils;
import com.fs.jzzn.pojo.Expense;
import com.fs.jzzn.pojo.Project;
import com.fs.jzzn.pojo.TaskCandidateUsers;
import com.fs.jzzn.repository.ExpenseRepository;
import com.fs.jzzn.repository.ProjectRepository;
import com.fs.jzzn.repository.TaskCandidateUsersRepository;

/**
 * @author TiddlerCJ
 * @desc 流程服务封装
 */
@AllArgsConstructor
@Data
@Service
@Transactional
@Log4j
public class ActivitiService {
	private RuntimeService runtimeService;
	private TaskService taskService;
	private FormService formService;
	private RepositoryService repositoryService;
	private ProjectRepository projectRepository;
	private BaseService baseService;
	private HistoryService historyService;
	private ExpenseRepository expenseRepository;
	private SqlRepository sqlRepository;
	private TaskCandidateUsersRepository taskCandidateUsersRepository;
	private OrgRepository orgRepository;
	private ProcessEngine processEngine;

	/**
	 * 流程部署
	 */
	public boolean deploy(String flowName, File zipFile) {
		boolean flag = false;
		try {
			/*ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
			Deployment deployment = repositoryService.createDeployment()  
					.addZipInputStream(zipInputStream)  
					.name(flowName)
					.deploy(); */
			
			ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
			Deployment deployment= processEngine.getRepositoryService() // 获取部署相关Service
					.createDeployment() // 创建部署
					.addZipInputStream(zipInputStream) // 添加zip输入流
					.name(flowName) // 流程名称
					.deploy(); // 部署
			if(deployment!=null){ flag = true; }
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return flag;
	}
	
	/**
	 * 分页查询部署对象列表
	 * @param firstResult
	 * @param maxResults
	 * @return
	 */
	public List<Deployment> findDeployList(){
		return  repositoryService.createDeploymentQuery().orderByDeploymenTime().desc().list();
	}
	
	/**
	 * 流程启动
	 */
	public void start(){
	}
	
	/**
	 * 待办任务
	 */
	public List<Task> myTasks(){
		return null;
	}
	
	/**
	 * 执行任务
	 */
	public void excuteTask(){
		
	}

	public void deleteDeploymentById(String deployId) {
		repositoryService.deleteDeployment(deployId,true);
	}

	/**
	 * 查询流程定义集合
	 * @return
	 */
	public List<ProcessDefinition> findProcessDefinitionList(String deployId) {
		return repositoryService.createProcessDefinitionQuery().deploymentId(deployId).orderByProcessDefinitionVersion().desc().list();
	}

	/**
	 * 获取流程定义图资源流
	 * @param deploymentId
	 * @param resourceName
	 * @return
	 */
	public InputStream getProcessDefImage(String deploymentId, String resourceName) {
		return	repositoryService.getResourceAsStream(deploymentId, resourceName);
	}

	/**
	 * 获取待办任务列表
	 * @param nickName
	 * @param taskName
	 */
	public List<TaskVo> getTodoList(String nickName, String taskName,PageRequest page) {
		if(StringUtils.isBlank(taskName)) taskName = "";
		List<TaskVo> taskList = new ArrayList<>();
		List<Task> list = taskService.createTaskQuery()
						//.taskCandidateUser(nickName)
						.taskCandidateOrAssigned(nickName)
						.taskNameLike("%"+ taskName +"%")
						.orderByTaskCreateTime()
						.asc()
						.list(); // 返回带分页的结果集合
		for(Task t: list){
			TaskVo vo = new TaskVo(t.getId(), t.getName(), t.getCreateTime(), null,nickName,null,null,null,null);
	    	String processInstanceId = t.getProcessInstanceId();
	    	HistoricProcessInstance hp = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
	    	if(hp!=null){
	    		vo.setBusinessKey(hp.getBusinessKey());
	    		vo.setFlowName(hp.getName());
	    		vo.setStartUser(hp.getStartUserId());
	    		vo.setStartTime(hp.getStartTime());
	    	}
	    	taskList.add(vo);
		}
		return taskList;
	}
	
	/**
	 * 开启工程流程
	 * @param project
	 * @return
	 */
	/*@Transactional
	public boolean startProjectProcess(Project project ){
		boolean flag = false;
		try {
			//流程定义Key及业务ID封装
			String processDefinitionKey = project.getClass().getSimpleName();
			String businessKey = processDefinitionKey + "." +  project.getId();
			
			//设置下个节点办理人
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("inputUser",ApplicationUtils.User().getNickName());
			variables.put("projectId",project.getId());
			
			//启动流程
			Authentication.setAuthenticatedUserId(ApplicationUtils.User().getNickName());
			ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
			runtimeService.setProcessInstanceName(pi.getId(),"单项工程" + project.getPNo().concat("[").concat(project.getPRoad()).concat("]") );
			
			//完成新建状态
			variables.put("outcome","提交");
			
			//String orgNo = project.getOrgNo();
			//String nextInputUser = QueryMap.projectCandidateUserMap.get(orgNo).getString("施工");
			//variables.put("inputUser",nextInputUser);
			
			Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult(); // 根据流程实例Id查询任务
			Authentication.setAuthenticatedUserId(ApplicationUtils.User().getNickName());
			taskService.complete(task.getId(),variables);  // 完成用户申请任务
			
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}*/
	
	@Transactional
	public boolean startProjectProcess(Project project){
		boolean flag = false;
		try {
			//流程定义Key及业务ID封装
			String processDefinitionKey = project.getClass().getSimpleName();
			String businessKey = processDefinitionKey + "." +  project.getId();
			
			/*
			 * 设置工程支出表单id
			 */
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("inputUser",ApplicationUtils.User().getNickName());
			variables.put("projectId",project.getId());
			
			Authentication.setAuthenticatedUserId(ApplicationUtils.User().getNickName());
			ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey,variables);
			/*
			 * 更新名称
			 */
			runtimeService.setProcessInstanceName(pi.getId(),"单项工程" + project.getPNo().concat("[").concat(project.getPRoad()).concat("]") );
			
			
			variables.put("outcome","提交");
			
			Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult(); // 根据流程实例Id查询任务
			
			//taskService.addCandidateGroup(taskId, groupId);
			//taskService.addCandidateUser(taskId, userId);
			
			/*
			 * 新建批注记录添加
			 */
			String comment =  "["+ task.getName() +"]提交";
			variables.put("comment", comment);
			taskService.addComment(task.getId(), pi.getId(), comment);
			
			// 完成用户申请任务
			taskService.complete(task.getId(),variables);
			
			/*
			 * 流程实例id回填到业务记录
			 */
			project.setProcessInstanceId(pi.getId());
			projectRepository.save(project);
			
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		return flag;
	}
	
	@Transactional
	public boolean startExpenseProcess(Expense expense){
		boolean flag = false;
		try {
			//流程定义Key及业务ID封装
			String processDefinitionKey = expense.getClass().getSimpleName();
			String businessKey = processDefinitionKey + "." +  expense.getId();
			
			/*
			 * 设置工程支出表单id
			 */
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("inputUser",ApplicationUtils.User().getNickName());
			variables.put("expenseId",expense.getId());
			
			Authentication.setAuthenticatedUserId(ApplicationUtils.User().getNickName());
			ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey,variables);
			/*
			 * 更新名称
			 */
			runtimeService.setProcessInstanceName(pi.getId(),"工程支出".concat(expense.getExpenseNo() + "流程") );
			
			Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult(); // 根据流程实例Id查询任务
			
			/*
			 * 新建批注记录添加
			 */
			String comment =  "["+ task.getName() +"]提交";
			variables.put("comment", comment);
			variables.put("outcome","提交");
			taskService.addComment(task.getId(), pi.getId(), comment);

			// 完成用户申请任务
			taskService.setAssignee(task.getId(), ApplicationUtils.User().getNickName());
			taskService.complete(task.getId(),variables);  
			
			/*
			 * 流程实例id回填到业务记录
			 */
			expense.setProcessInstanceId(pi.getId());
			expenseRepository.save(expense);
			
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		return flag;
	}
	
	public void deleteProcessInstance(String proId){
		getRuntimeService().deleteProcessInstance(proId,"错误实例[id"+ proId + "]");//删除流程
		getHistoryService().deleteHistoricProcessInstance(proId);
	}
	
	
	/**
	 * 启动工程支出流程
	 * @param expense
	 * @return
	 */
	/*@Transactional
	public boolean startExpenseProcess(Expense expense,String inputUser ,User leader){
		boolean flag = false;
		try {
			//流程定义Key及业务ID封装
			String processDefinitionKey = expense.getClass().getSimpleName();
			String businessKey = processDefinitionKey + "." +  expense.getId();
			
			
			 * 设置工程支出表单id
			 
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("expenseId",expense.getId());
			variables.put("inputUser",inputUser);
			Authentication.setAuthenticatedUserId(ApplicationUtils.User().getNickName());
			ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey,variables);
			
			 * 更新名称
			 
			runtimeService.setProcessInstanceName(pi.getId(),"工程支出".concat(expense.getExpenseNo() + "流程") );
			
			Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult(); // 根据流程实例Id查询任务
			
			
			 * 新建批注记录添加
			 
			Authentication.setAuthenticatedUserId(ApplicationUtils.User().getNickName());
			String comment =  "["+ task.getName() +"]提交";
			variables.put("comment", comment);
			taskService.addComment(task.getId(), pi.getId(), comment);
			
			 * 自动填写表单
			 
			variables.put("outcome","提交");
			taskService.complete(task.getId(),variables);  // 完成用户申请任务   
			flag = true;
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		return flag;
	}*/
	
	
	/**
	 * 根据taskId查询流程定义
	 * @param taskId
	 * @return
	 */
	public ProcessDefinition findProcessDefinitionByTaskId(String taskId){
		Task task = findTaskById(taskId);
		
		return repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(task.getProcessDefinitionId()).singleResult();
	}
	
	/**
	 * 获取当前节点位置数据集合
	 * @param taskId
	 * @return
	 */
	public Map<String, Object> findCoordingMapByTaskId(String taskId){
		Map<String, Object> data = new HashMap<>();
		//当前节点
		Task task =  findTaskById(taskId);
		//流程定义
		ProcessDefinitionEntity pdEntity = (ProcessDefinitionEntity) findProcessDefinitionByTaskId(taskId);
		
		String processInstanceId = task.getProcessInstanceId();
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		
		String activityId = pi.getActivityId();
	
		ActivityImpl activity = pdEntity.findActivity(activityId);
		if(activity!=null){
			data.put("x", activity.getX());
			data.put("y", activity.getY());
			data.put("width", activity.getWidth());
			data.put("height", activity.getHeight());
		}
		
		/*// 查看当前活动坐标
		ProcessDefinitionEntity processDefinitionEntity =(ProcessDefinitionEntity) repositoryService.getProcessDefinition(processDefinitionId);
		String processInstanceId = hti.getProcessInstanceId(); // 获取流程实例id
		// 根据流程实例id查询活动实例
		ProcessInstance pi =runtimeService.createProcessInstanceQuery()
				.processInstanceId(processInstanceId)  
				.singleResult();
		ActivityImpl activityImpl = processDefinitionEntity.findActivity(pi.getActivityId()); // 根据活动id查询活动实例
		mav.addObject("x", activityImpl.getX());
		mav.addObject("y", activityImpl.getY());
		mav.addObject("width", activityImpl.getWidth());
		mav.addObject("height", activityImpl.getHeight());*/
		return data;
	}
	
	/**
	 * 获取当前任务节点表单formkey
	 * @param taskId
	 * @return
	 */
	public String findTaskFormKeyByTaskId(String taskId){
		return formService.getTaskFormData(taskId).getFormKey();
	}
	
	public Project findBusinessObjectByTaskId(String taskId){
		Task task = findTaskById(taskId);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult();
		String businessKey = pi.getBusinessKey();
		if(StringUtils.isNotBlank(businessKey)){
			String[] objs = businessKey.split("\\.");
			return projectRepository.findOne(objs[1]);
		}else{
			return null;
		}
	}
	
	public String getBusinessKeyByTaskId(String taskId){
		Task task = findTaskById(taskId);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult();
		return pi.getBusinessKey();
	}
	
	public String findBusinessIdByTaskId(String taskId){
		Task task = findTaskById(taskId);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult();
		String businessKey = pi.getBusinessKey();
		if(StringUtils.isNotBlank(businessKey)){
			String[] objs = businessKey.split("\\.");
			return objs[1] ;
		}else{
			return null;
		}
	}
	

	public Set<String> findTaskLinesByTaskId(String taskId) {
		Set<String> outLines = new HashSet<String>();
		Task task =  findTaskById(taskId);
		String pdId= task.getProcessDefinitionId();
		ProcessDefinitionEntity pDefinitionEntity = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(pdId);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
		String activityId = pi.getActivityId();
		ActivityImpl activity = pDefinitionEntity.findActivity(activityId);
		List<PvmTransition> list = activity.getOutgoingTransitions();
		if(!CollectionUtils.isEmpty(list)){
			for(PvmTransition pvm:list){
				String outName = (String)pvm.getProperty("name");
				if(StringUtils.isBlank(outName)){
					outLines.add("默认提交");
				}else{
					outLines.add(outName);
				}
			}
		}
		return outLines;
	}
	
	
	public String findTaskCandidataUsersByTaskId(String taskId) {
		String candidateUsers = "";
		Task task =  findTaskById(taskId);
		String pdId= task.getProcessDefinitionId();
		ProcessDefinitionEntity pDefinitionEntity = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(pdId);
		String processKey = pDefinitionEntity.getKey();
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
		String activityId = pi.getActivityId();
		ActivityImpl activity = pDefinitionEntity.findActivity(activityId);
		if(activity!=null){
			TaskCandidateUsers user = taskCandidateUsersRepository.findByProcessKeyAndTaskId(processKey, taskId);
			if(user!=null && StringUtils.isNotBlank(user.getCandidateUsers())){
				candidateUsers = user.getCandidateUsers();
			}
		}
		return candidateUsers;
	}
	
	public Task findTaskById(String taskId){
		return taskService.createTaskQuery().taskId(taskId).singleResult();
	}

	public List<TaskVo> getHasdoList(String nickName, String taskName, PageRequest page) {
		if(StringUtils.isBlank(taskName)){ taskName = ""; }
		/*List<HistoricTaskInstance> htiList =historyService.createHistoricTaskInstanceQuery() // 创建历史任务实例查询
				//.taskCandidateGroup(groupId) // 根据角色查询
				.taskNameLike("%"+taskName+"%") // 根据任务名称模糊查询
				.list(); // 返回带分页的结果集合
		List<TaskVo> taskList=new ArrayList<TaskVo>();
		for(HistoricTaskInstance hti:htiList){
			// 如果该任务对应的流程实例在运行时任务表里查询到，说明就是这个流程实例未走完  并且用用户id以及任务id在运行时候任务表里查询不到结果  才算是已办任务
		    if((taskService.createTaskQuery().processInstanceId(hti.getProcessInstanceId()).singleResult()!=null)
		    		&&(taskService.createTaskQuery().taskCandidateOrAssigned(nickName).taskId(hti.getId()).list().size()==0)){  
		    	TaskVo myTask= new TaskVo(hti.getId(), hti.getName(), hti.getCreateTime(), hti.getEndTime());
		    	taskList.add(myTask);
		    }
		}*/
		List<TaskVo> taskList=new ArrayList<TaskVo>();
		List<HistoricTaskInstance> list1= historyService // 历史任务Service
	            .createHistoricTaskInstanceQuery() // 创建历史任务实例查询
	            .taskInvolvedUser(nickName)
	            .taskNameLike("%"+ taskName+ "%")
	            .finished() // 查询已经完成的任务  
	            .list();
		/*List<HistoricTaskInstance> list1= historyService // 历史任务Service
		            .createHistoricTaskInstanceQuery() // 创建历史任务实例查询
		            .taskAssignee(nickName)
		            .taskNameLike("%"+ taskName+ "%")
		            .finished() // 查询已经完成的任务  
		            .list();
		  
		  List<HistoricTaskInstance> list2= historyService // 历史任务Service
		            .createHistoricTaskInstanceQuery() // 创建历史任务实例查询
		            .taskCandidateUser(nickName) // 指定办理人
		            .taskNameLike("%"+ taskName+ "%")
		            .finished() // 查询已经完成的任务  
		            .list();
		  list1.addAll(list2);*/
		    for(HistoricTaskInstance hti:list1){
		    	TaskVo vo = new TaskVo(hti.getId(), hti.getName(), hti.getCreateTime(), hti.getEndTime(),nickName,null,null,null,null);
		    	String processInstanceId = hti.getProcessInstanceId();
		    	HistoricProcessInstance hp = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		    	if(hp!=null){
		    		vo.setBusinessKey(hp.getBusinessKey());
		    		vo.setFlowName(hp.getName());
		    		
		    		vo.setStartUser(hp.getStartUserId());
		    		vo.setStartTime(hp.getStartTime());
		    		
		    		//System.out.println(hp.getStartUserId());
		    		//System.out.println(hp.getStartTime());
		    	}
		    	//System.out.println(hp.getBusinessKey());
		    	//System.out.println(hp.getName());
		    	taskList.add(vo);
		    	/* System.out.println("任务ID:"+hti.getId());
		        System.out.println("流程实例ID:"+hti.getProcessInstanceId());
		        System.out.println("班里人："+hti.getAssignee());
		        System.out.println("创建时间："+hti.getCreateTime());
		        System.out.println("结束时间："+hti.getEndTime());
		        System.out.println("===========================");*/
		    }
		
		return taskList;
	}

	/**
	 * 通过任务ID获取批注列表
	 * @param taskId
	 * @return
	 */
	public List<Comment> findCommentByTaskId(String taskId) {
		Task task = findTaskById(taskId);
		//HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
		String processInstanceId = task.getProcessInstanceId(); // 获取流程实例id
		List<Comment> comments=taskService.getProcessInstanceComments(processInstanceId);
		return comments;
	}

	/**
	 * 通过业务id查找批注信息
	 * @param projectId
	 * @return
	 */
	public List<Comment> findCommentByBussnessId(String processInstanceBusinessKey) {
		HistoricProcessInstance hisP =  historyService.createHistoricProcessInstanceQuery()
					.processInstanceBusinessKey(processInstanceBusinessKey)
					.singleResult();
		if(hisP!=null){
			return taskService.getProcessInstanceComments(hisP.getId());
		}else{
			return new ArrayList<Comment>();
		}
	}

	/**
	 * 获取最新版本流程定义
	 * @return
	 */
	public List<ProcessDefinition> findProcessDefinitionMaxVersion(String name) {
		List<ProcessDefinition> list =  null;
		if(StringUtils.isNotBlank(name)){
			list =  repositoryService.createProcessDefinitionQuery().processDefinitionNameLike("%"+ name+ "%").orderByProcessDefinitionVersion().latestVersion().asc().list();
		}else{
			list =  repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().latestVersion().asc().list();
		}
		Map<String, ProcessDefinition> map = new LinkedHashMap<>();
		for(ProcessDefinition pd: list){
			map.put(pd.getKey(), pd);
		}
		List<ProcessDefinition> resultList =new LinkedList<ProcessDefinition>(map.values());
		return resultList;
	}
	
	public Object getBusinessObj(String executionId){
		Object obj = runtimeService.getVariable(executionId, "businessObj");
		return obj;
	}
	
	public Page<Affair> affairPage(String sql,Map<Object, Object> params,Pageable pageable){
		return sqlRepository.page(sql, params, pageable, Affair.class);
	} 
	
	/**
	 * 更新节点候选人
	 * @param user
	 */
	public void updateTaskCandidateUser(TaskCandidateUsers user){
		if(StringUtils.isNotBlank(user.getProcessKey()) && 
				StringUtils.isNotBlank(user.getTaskId())){
			taskCandidateUsersRepository.deleteByProcessKeyAndTaskId(user.getProcessKey(), user.getTaskId());
			taskCandidateUsersRepository.save(user);
		}
	}
	
	/**
	 * 通过流程的key获取流程定义模型
	 * @param key
	 * @return
	 */
	public BpmnModel getBpmnModel(String key){
		BpmnModel model = null;
		RepositoryService repositoryService = getRepositoryService() ;
	    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
	    		.processDefinitionKey(key).latestVersion().singleResult();
	    String resourceName = processDefinition.getResourceName();
	    InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),
	            resourceName);
	    try {
			//创建转换对象
			BpmnXMLConverter converter = new BpmnXMLConverter();
			XMLInputFactory factory = XMLInputFactory.newInstance();
			XMLStreamReader reader = factory.createXMLStreamReader(resourceAsStream);//createXmlStreamReader
			//将xml文件转换成BpmnModel
			model = converter.convertToBpmnModel(reader);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	    return model;
	}
}
